package service

import (
	"admin-go-api/pkg/captcha"
	"encoding/json"
	"fmt"
	"github.com/wenlng/go-captcha-assets/helper"
	"github.com/wenlng/go-captcha/v2/base/option"
	"log"
)

func CaptSideMake() string {
	//生成验证码
	captData, err := captcha.SlideCapt.Generate()
	if err != nil {
		log.Fatalln(err)
	}
	//获取验证码数据
	blockData := captData.GetData()
	if blockData == nil {
		log.Fatalln(">>>>> generate err")
	}
	//使用json.Marshal函数将blockData转换为 JSON 格式的字节切片dots
	dotsByte, _ := json.Marshal(blockData)
	var masterImageBase64, tileImageBase64 string
	masterImageBase64, err = captData.GetMasterImage().ToBase64()
	if err != nil {
		fmt.Println(err)
	}
	tileImageBase64, err = captData.GetTileImage().ToBase64()
	if err != nil {
		fmt.Println(err)
	}
	key := helper.StringToMD5(string(dotsByte))
	//cache.WriteCache(key, dotsByte)

	dots, _ := json.Marshal(map[string]interface{}{
		"code":         0,
		"captcha_key":  key,
		"image_base64": masterImageBase64,
		"tile_base64":  tileImageBase64,
		"tile_width":   blockData.Width,
		"tile_height":  blockData.Height,
		"tile_x":       blockData.TileX,
		"tile_y":       blockData.TileY,
	})
	fmt.Println(">>>>> ", string(dots))

	err = captData.GetMasterImage().SaveToFile("./.caches/master.jpg", option.QualityNone)
	if err != nil {
		fmt.Println(err)
	}
	err = captData.GetTileImage().SaveToFile("./.caches/thumb.png")
	if err != nil {
		fmt.Println(err)
	}
	return string(dots)
}
